﻿using System;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using QSWcfServiceLibrary;
using QSWPFApplicationCSharp.PersonWCFService;
using ValidationFramework;

namespace QSWPFApplicationCSharp
{
    /// <summary>
    /// Interaction logic for WcfWindow.xaml
    /// </summary>
    public partial class WcfWindow : Window
    {
        public WcfWindow()
        {
            InitializeComponent();
        }

        private void closeButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void submitButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var personServiceClient = new PersonServiceClient())
                {
                    var person = new Person();

                    int age;
                    if (int.TryParse(ageTextBox.Text, out age))
                    {
                        person.Age = age;
                    }

                    personServiceClient.SavePerson(person);
                }
            }

            catch (FaultException<ValidationFaultException> exception)
            {
                errorTreeView.Items.Clear();
                foreach (var keyValuePair in exception.Detail.ValidationErrors)
                {
                    var node = new TreeViewItem { Header = keyValuePair.Key };
                    foreach (var errorMessage in keyValuePair.Value)
                    {
                        node.Items.Add(errorMessage);
                    }
                    errorTreeView.Items.Add(node);
                }
            }
        }

        private void validateButton_Click(object sender, RoutedEventArgs e)
        {
            errorTreeView.Items.Clear();
            var person = new Person();

            int age;
            if (int.TryParse(ageTextBox.Text, out age))
            {
                person.Age = age;
            }

            var propertyValidationManager = new PropertyValidationManager(person);
            propertyValidationManager.ValidateAll();

            foreach (var result in propertyValidationManager.ValidatorResultsInError)
            {
                var node = new TreeViewItem {Header = result.ErrorMessage};
                node.Items.Add(String.Format("RuleInterpretation = '{0}'", result.Rule.RuleInterpretation));
                node.Items.Add(String.Format("Rule = '{0}'", result.Rule.GetType()));
                errorTreeView.Items.Add(node);
            }
        }
    }
}
